class WebSocketClient {
    constructor(url) {
        this.url = url;
        this.socket = null;
        this.callbacks = {};
        this.heartbeatInterval = 30000; // 心跳间隔时间
        this.isAlive = true; // 用于标记连接是否存活
        this.connect();
        this.setupHeartbeat();
    }

    setupHeartbeat() {
        // 发送心跳
        const ping = () => {
            if (this.socket.readyState === WebSocket.OPEN) {
                this.send('ping', null); // 假设服务器约定'ping'作为心跳信号
                this.isAlive = false; // 发送心跳后标记为未确认存活
            }
        };

        // 开始心跳定时器
        this.pingTimer = setInterval(ping, this.heartbeatInterval);

        // 监听message事件，检查心跳回应
        this.socket.addEventListener('message', (event) => {
            const message = event.data
            if (message) {
                this.isAlive = true; // 收到回应则标记连接存活
            }
        });

        // 当连接关闭时清除心跳定时器
        this.socket.addEventListener('close', () => {
            clearInterval(this.pingTimer);
        });
    }

    checkHeartbeat() {
        // 可以在这里添加逻辑来判断是否需要根据isAlive状态做出反应，比如重连
        if (!this.isAlive) {
            console.log('心跳检测失败，考虑重连或采取其他措施');
            // 这里可以调用disconnect和connect方法尝试重连
        }
    }

    connect() {
        this.socket = new WebSocket(this.url);

        this.socket.addEventListener('open', (event) => {
            if (typeof this.onOpen === 'function') {
                this.onOpen(event);
            }
        });

        this.socket.addEventListener('message', (event) => {
            const message = event.data !== 'ping' && JSON.parse(event.data);
            if (this.callbacks['message']) {
                this.callbacks['message'](message);
            }
        });

        this.socket.addEventListener('error', (error) => {
            console.error('WebSocket错误:', error);
            if (typeof this.onError === 'function') {
                this.onError(error);
            }
        });

        this.socket.addEventListener('close', (event) => {
            if (typeof this.onClose === 'function') {
                this.onClose(event);
            }
        });
    }

    send(type, data) {
        if (this.socket.readyState === WebSocket.OPEN) {
            const message = JSON.stringify({ type, data });
            this.socket.send(message);
        } else {
            console.error('WebSocket连接未打开，无法发送消息');
        }
    }

    on(type, callback) {
        console.log(333)
        this.callbacks[type] = callback;
    }

    onClose(callback) {
        this.onClose = callback;
    }

    onError(callback) {
        this.onError = callback;
    }

    onOpen(callback) {
        this.onOpen = callback;
    }

    disconnect() {
        if (this.socket && this.socket.readyState === WebSocket.OPEN) {
            this.socket.close();
        }
    }
}

export default WebSocketClient;